package com.elvish.oda.busin.service;

import java.util.ArrayList;
import java.util.List;

import org.nutz.lang.Lang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.elvish.oda.busin.dao.PermissionDao;
import com.elvish.oda.busin.pojo.Permission;

@Component
public class PermissionService {

	@Autowired
	private PermissionDao permissionDao;

	public List<Permission> findAll() {
		return permissionDao.findAll();
	}

	public Permission findById(Integer id) {
		return permissionDao.findById(id);
	}

	public int save(Permission permission) {
		return permissionDao.save(permission);
	}

	@Transactional
	public int deleteById(Integer id) {
		List<String> ids = new ArrayList<String>();
		List<Permission> childrenList = permissionDao.findByPid(id);
		// 根据id查询其下级所有数据id
		findById(childrenList, ids);
		// 自身
		ids.add(id.toString());
		// 删除所有数据
		permissionDao.deleteByIds(ids.toArray(new String[ids.size()]));
		return 1;

	}

	public int update(Permission permission) {
		return permissionDao.update(permission);
	}

	public List<Permission> findByRoleId(Integer roleId) {
		return permissionDao.findByRoleId(roleId);
	}

	public void findById(List<Permission> childrenList, List<String> ids) {
		if (!Lang.isEmpty(childrenList)) {
			for (Permission permission : childrenList) {
				// 根据id查询pid为id的下级
				List<Permission> childList = permissionDao.findByPid(permission.getId());
				ids.add(permission.getId().toString());
				findById(childList, ids);
			}
		}
	}

	@Transactional
	public int assignPermissions(Integer roleId, String[] ids) {
		// 删除角色已有权限
		permissionDao.deleteByRoleId(roleId);
		// 录入新分配的权限
		permissionDao.savePermissionsWithRoleId(roleId, ids);
		return 1;
	}

}
